package com.roger.springcloudGreenwich.api;


import com.roger.springcloudGreenwich.bean.Student;
import com.roger.springcloudGreenwich.service.RedisIdGenerator;
import com.roger.springcloudGreenwich.dao.StudentDao;
import com.roger.springcloudGreenwich.jwt.JwtUtil;
import com.roger.springcloudGreenwich.utils.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by admin on 2020/3/30.
 */
@RestController
@Slf4j
public class ElasticSearchController {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private StudentDao studentDao;

    @Autowired
    private RedisIdGenerator redisIdGenerator;

    @GetMapping("/getClient")
    public Object getClient(){
        return restHighLevelClient;
    }

    @GetMapping("/addClient")
    public Object addClient(){
        List<Student> docs  = new ArrayList<>();
        Student s;
        try {
            for(int i = 0; i < 10; i++){
                s = new Student();
                s.setName("tome" + i);
                s.setAge(12 + i);
                s.setId(UUID.randomUUID().toString());
                s.setData(ObjectUtils.objectToMap(s));
                docs.add(s);
            }
            studentDao.async("students","doc",docs);
        }catch (Exception e){
            e.printStackTrace();
        }

        return "success";
    }

    @GetMapping("query/{age}")
    public Object query(@PathVariable int age, HttpServletResponse response){
        studentDao.query(age);
        String accessToken = JwtUtil.getToken("admin");
        String refreshToken = JwtUtil.getToken("admin2");
        response.addHeader("access_token", accessToken);
        response.addHeader("refresh_token", refreshToken);
        return "success";
    }


    @GetMapping("indexExist/{index}")
    public boolean indexExist(@PathVariable String index){
        return studentDao.indexExist(index);
    }


    //https://blog.csdn.net/little_stick_i/article/details/125406922
    @GetMapping("/getId")
    public void getId(){
        ExecutorService executor = Executors.newCachedThreadPool();
        for (int i = 0; i < 1000; i++) {
            final int index = i;
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println((new Date()) + ":" + redisIdGenerator.nextId("distributeId"));
                }
            });
        }
    }

}

